<template>
  <div class="order-detail">
    <el-page-header @back="goBack" :title="'订单详情'" />
    
    <!-- 订单基本信息 -->
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>基本信息</span>
          <div class="header-actions">
            <el-button type="primary" @click="handlePrint" v-if="orderInfo.status === 'completed'">
              <el-icon><Printer /></el-icon>打印订单
            </el-button>
            <el-button 
              type="success" 
              @click="handleConfirm" 
              v-if="orderInfo.status === 'pending_confirm'"
              v-permission="'merchant:order:confirm'"
            >
              确认订单
            </el-button>
            <el-button 
              type="primary" 
              @click="handleStartService" 
              v-if="orderInfo.status === 'pending_service'"
              v-permission="'merchant:order:service'"
            >
              开始服务
            </el-button>
            <el-button 
              type="success" 
              @click="handleComplete" 
              v-if="orderInfo.status === 'in_service'"
              v-permission="'merchant:order:complete'"
            >
              完成服务
            </el-button>
            <el-button 
              type="danger" 
              @click="handleCancel" 
              v-if="['pending_payment', 'pending_confirm'].includes(orderInfo.status)"
              v-permission="'merchant:order:cancel'"
            >
              取消订单
            </el-button>
            <el-button 
              type="warning" 
              @click="handleRefund" 
              v-if="orderInfo.status === 'completed'"
              v-permission="'merchant:order:refund'"
            >
              申请退款
            </el-button>
          </div>
        </div>
      </template>
      
      <el-descriptions :column="3" border>
        <el-descriptions-item label="订单编号">{{ orderInfo.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getOrderStatusTag(orderInfo.status)">
            {{ getOrderStatusLabel(orderInfo.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="订单金额">¥{{ orderInfo.amount?.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="客户姓名">{{ orderInfo.customerName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ orderInfo.customerPhone }}</el-descriptions-item>
        <el-descriptions-item label="电子邮箱">{{ orderInfo.customerEmail }}</el-descriptions-item>
        <el-descriptions-item label="服务项目">{{ orderInfo.serviceName }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ getPaymentMethodLabel(orderInfo.paymentMethod) }}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ orderInfo.paymentTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ orderInfo.createTime }}</el-descriptions-item>
        <el-descriptions-item label="预约时间">{{ orderInfo.appointmentTime }}</el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ orderInfo.completeTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="3">{{ orderInfo.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 服务详情 -->
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>服务详情</span>
        </div>
      </template>
      
      <el-table :data="orderInfo.serviceItems" border>
        <el-table-column prop="name" label="服务项目" min-width="150" />
        <el-table-column prop="price" label="单价" width="120">
          <template #default="{ row }">
            ¥{{ row.price?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="100" />
        <el-table-column prop="amount" label="小计" width="120">
          <template #default="{ row }">
            ¥{{ row.amount?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
      </el-table>

      <div class="order-summary">
        <div class="summary-item">
          <span>商品总额：</span>
          <span>¥{{ orderInfo.goodsAmount?.toFixed(2) }}</span>
        </div>
        <div class="summary-item">
          <span>优惠金额：</span>
          <span>-¥{{ orderInfo.discountAmount?.toFixed(2) }}</span>
        </div>
        <div class="summary-item total">
          <span>实付金额：</span>
          <span>¥{{ orderInfo.amount?.toFixed(2) }}</span>
        </div>
      </div>
    </el-card>

    <!-- 订单状态记录 -->
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>状态记录</span>
        </div>
      </template>
      
      <el-timeline>
        <el-timeline-item
          v-for="(log, index) in orderInfo.statusLogs"
          :key="index"
          :type="getTimelineItemType(log.status)"
          :timestamp="log.time"
        >
          {{ getOrderStatusLabel(log.status) }}
          <div class="timeline-content" v-if="log.remark">
            {{ log.remark }}
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-card>

    <!-- 操作记录 -->
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>操作记录</span>
        </div>
      </template>
      
      <el-table :data="orderInfo.operationLogs" border>
        <el-table-column prop="operator" label="操作人" width="120" />
        <el-table-column prop="action" label="操作" width="120" />
        <el-table-column prop="time" label="操作时间" min-width="180" />
        <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
      </el-table>
    </el-card>

    <!-- 评价信息 -->
    <el-card class="detail-card" v-if="orderInfo.review">
      <template #header>
        <div class="card-header">
          <span>评价信息</span>
        </div>
      </template>
      
      <div class="review-content">
        <div class="review-header">
          <div class="review-rating">
            <el-rate v-model="orderInfo.review.rating" disabled />
            <span class="rating-text">{{ orderInfo.review.rating }}分</span>
          </div>
          <div class="review-time">{{ orderInfo.review.createTime }}</div>
        </div>
        <div class="review-text">{{ orderInfo.review.content }}</div>
        <div class="review-images" v-if="orderInfo.review.images?.length">
          <el-image
            v-for="(image, index) in orderInfo.review.images"
            :key="index"
            :src="image"
            :preview-src-list="orderInfo.review.images"
            fit="cover"
            class="review-image"
          />
        </div>
        <div class="review-reply" v-if="orderInfo.review.reply">
          <div class="reply-header">商家回复：</div>
          <div class="reply-content">{{ orderInfo.review.reply }}</div>
          <div class="reply-time">{{ orderInfo.review.replyTime }}</div>
        </div>
      </div>
    </el-card>

    <!-- 退款信息 -->
    <el-card class="detail-card" v-if="orderInfo.refund">
      <template #header>
        <div class="card-header">
          <span>退款信息</span>
          <el-tag :type="getRefundStatusTag(orderInfo.refund.status)">
            {{ getRefundStatusLabel(orderInfo.refund.status) }}
          </el-tag>
        </div>
      </template>
      
      <el-descriptions :column="2" border>
        <el-descriptions-item label="退款金额">¥{{ orderInfo.refund.amount?.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="退款状态">
          <el-tag :type="getRefundStatusTag(orderInfo.refund.status)">
            {{ getRefundStatusLabel(orderInfo.refund.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="退款原因">{{ orderInfo.refund.reason }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ orderInfo.refund.createTime }}</el-descriptions-item>
        <el-descriptions-item label="处理时间">{{ orderInfo.refund.processTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="处理备注">{{ orderInfo.refund.processRemark || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 退款对话框 -->
    <el-dialog
      v-model="refundDialogVisible"
      title="申请退款"
      width="500px"
    >
      <el-form
        ref="refundFormRef"
        :model="refundForm"
        :rules="refundRules"
        label-width="100px"
      >
        <el-form-item label="退款金额" prop="amount">
          <el-input-number 
            v-model="refundForm.amount" 
            :min="0" 
            :max="orderInfo.amount"
            :precision="2"
            :step="0.01"
          />
        </el-form-item>
        <el-form-item label="退款原因" prop="reason">
          <el-input
            v-model="refundForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入退款原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="refundDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRefundSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Printer } from '@element-plus/icons-vue'
import {
  getMerchantOrderDetail,
  updateMerchantOrderStatus,
  refundMerchantOrder,
  printMerchantOrder
} from '@/api/merchant'

const route = useRoute()
const router = useRouter()

// 订单信息
const orderInfo = ref({})

// 退款对话框
const refundDialogVisible = ref(false)
const refundFormRef = ref(null)
const refundForm = reactive({
  amount: 0,
  reason: ''
})

// 退款表单验证规则
const refundRules = {
  amount: [
    { required: true, message: '请输入退款金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '退款金额必须大于0', trigger: 'blur' }
  ],
  reason: [
    { required: true, message: '请输入退款原因', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

// 获取订单详情
const getOrderDetail = async () => {
  try {
    const { data } = await getMerchantOrderDetail(route.params.id)
    orderInfo.value = data
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取订单状态标签类型
const getOrderStatusTag = (status) => {
  const statusMap = {
    pending_payment: 'warning',
    pending_confirm: 'info',
    pending_service: 'primary',
    in_service: 'success',
    completed: 'success',
    cancelled: 'danger',
    refunded: 'info'
  }
  return statusMap[status] || ''
}

// 获取订单状态标签文本
const getOrderStatusLabel = (status) => {
  const statusMap = {
    pending_payment: '待付款',
    pending_confirm: '待确认',
    pending_service: '待服务',
    in_service: '服务中',
    completed: '已完成',
    cancelled: '已取消',
    refunded: '已退款'
  }
  return statusMap[status] || status
}

// 获取支付方式标签文本
const getPaymentMethodLabel = (method) => {
  const methodMap = {
    wechat: '微信支付',
    alipay: '支付宝',
    balance: '余额支付',
    cash: '现金支付'
  }
  return methodMap[method] || method
}

// 获取时间线项目类型
const getTimelineItemType = (status) => {
  const typeMap = {
    pending_payment: 'warning',
    pending_confirm: 'info',
    pending_service: 'primary',
    in_service: 'success',
    completed: 'success',
    cancelled: 'danger',
    refunded: 'info'
  }
  return typeMap[status] || ''
}

// 获取退款状态标签类型
const getRefundStatusTag = (status) => {
  const statusMap = {
    pending: 'warning',
    processing: 'primary',
    approved: 'success',
    rejected: 'danger'
  }
  return statusMap[status] || ''
}

// 获取退款状态标签文本
const getRefundStatusLabel = (status) => {
  const statusMap = {
    pending: '待处理',
    processing: '处理中',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return statusMap[status] || status
}

// 确认订单
const handleConfirm = async () => {
  try {
    await ElMessageBox.confirm('确认接受该订单吗？', '提示', {
      type: 'warning'
    })
    await updateMerchantOrderStatus(orderInfo.value.id, { status: 'pending_service' })
    ElMessage.success('订单已确认')
    getOrderDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认订单失败:', error)
    }
  }
}

// 开始服务
const handleStartService = async () => {
  try {
    await ElMessageBox.confirm('确认开始服务吗？', '提示', {
      type: 'warning'
    })
    await updateMerchantOrderStatus(orderInfo.value.id, { status: 'in_service' })
    ElMessage.success('已开始服务')
    getOrderDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('开始服务失败:', error)
    }
  }
}

// 完成服务
const handleComplete = async () => {
  try {
    await ElMessageBox.confirm('确认完成服务吗？', '提示', {
      type: 'warning'
    })
    await updateMerchantOrderStatus(orderInfo.value.id, { status: 'completed' })
    ElMessage.success('服务已完成')
    getOrderDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成服务失败:', error)
    }
  }
}

// 取消订单
const handleCancel = async () => {
  try {
    await ElMessageBox.confirm('确认取消该订单吗？', '提示', {
      type: 'warning'
    })
    await updateMerchantOrderStatus(orderInfo.value.id, { status: 'cancelled' })
    ElMessage.success('订单已取消')
    getOrderDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
    }
  }
}

// 申请退款
const handleRefund = () => {
  refundForm.amount = orderInfo.value.amount
  refundForm.reason = ''
  refundDialogVisible.value = true
}

// 提交退款
const handleRefundSubmit = async () => {
  if (!refundFormRef.value) return
  
  try {
    await refundFormRef.value.validate()
    await refundMerchantOrder(orderInfo.value.id, refundForm)
    ElMessage.success('退款申请已提交')
    refundDialogVisible.value = false
    getOrderDetail()
  } catch (error) {
    console.error('提交退款失败:', error)
  }
}

// 打印订单
const handlePrint = async () => {
  try {
    await printMerchantOrder(orderInfo.value.id)
    ElMessage.success('打印成功')
  } catch (error) {
    console.error('打印订单失败:', error)
  }
}

onMounted(() => {
  getOrderDetail()
})
</script>

<style lang="scss" scoped>
.order-detail {
  padding: 20px;

  .detail-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
  }

  .order-summary {
    margin-top: 20px;
    padding: 20px;
    background-color: #f8f9fa;
    border-radius: 4px;

    .summary-item {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 10px;
      font-size: 14px;

      &:last-child {
        margin-bottom: 0;
      }

      &.total {
        font-size: 16px;
        font-weight: bold;
        color: #f56c6c;
      }
    }
  }

  .timeline-content {
    font-size: 13px;
    color: #666;
    margin-top: 5px;
  }

  .review-content {
    .review-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      .review-rating {
        display: flex;
        align-items: center;
        gap: 10px;

        .rating-text {
          font-size: 16px;
          font-weight: bold;
          color: #f56c6c;
        }
      }

      .review-time {
        color: #999;
        font-size: 14px;
      }
    }

    .review-text {
      font-size: 14px;
      line-height: 1.6;
      margin-bottom: 15px;
    }

    .review-images {
      display: flex;
      gap: 10px;
      margin-bottom: 15px;

      .review-image {
        width: 100px;
        height: 100px;
        border-radius: 4px;
      }
    }

    .review-reply {
      padding: 15px;
      background-color: #f8f9fa;
      border-radius: 4px;

      .reply-header {
        font-weight: bold;
        margin-bottom: 10px;
      }

      .reply-content {
        font-size: 14px;
        line-height: 1.6;
        margin-bottom: 10px;
      }

      .reply-time {
        color: #999;
        font-size: 12px;
        text-align: right;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 